package com.example.volleytest.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.ImageLoader;
import com.example.volleytest.R;
import com.example.volleytest.network.VolleyHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class StartActivity extends Activity {
    private static final String TAG = "KVEST_TAG";
    private static final String SELF_INFO_REQUEST_TAG = "self_info_tag";

    private ImageLoader.ImageContainer imageRequest;

    private TextView selfInfoTextView;
    private ImageView avatarImageView;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initUI();
        initVolley();
        requestSelfInfo();
    }

    private void initUI() {
        selfInfoTextView = (TextView) findViewById(R.id.self_info_tv);
        avatarImageView = (ImageView) findViewById(R.id.avatar_iv);
    }

    private void initVolley() {
        VolleyHelper.getInstance().init(getApplicationContext());
    }

    private void toast(String text) {
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
    }

    private void requestSelfInfo() {
        String url = "http://api.vk.com/method/users.get?uid=1&fields=photo_50,city,nickname&name_case=nom";
        JsonObjectRequest jsonRequest = new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() {
            public void onResponse(JSONObject result) {
                try {
                    parseSelfInfo(result);
                } catch (JSONException e) {
                    toast("JSONException=" + e.getMessage());
                }
            }
        }, new ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                toast("onErrorResponse=" + error.getMessage());
            }
        });

        jsonRequest.setTag(SELF_INFO_REQUEST_TAG);
        VolleyHelper.getInstance().addRequest(jsonRequest);
    }

    private void parseSelfInfo(JSONObject root) throws JSONException{
        Log.d(TAG, root.toString());
        if (root.has("response")) {
            JSONArray items = root.getJSONArray("response");
            if (items.length() > 0) {
                JSONObject self = items.getJSONObject(0);
                String last_name = self.getString("last_name");
                String first_name = self.getString("first_name");
                int uid = self.getInt("uid");
                String nickname = self.getString("nickname");
                String avatar_link = self.getString("photo_50");
                selfInfoTextView.setText("id=" + uid + "\n" + first_name + " " + last_name + "\n" + nickname);

                imageRequest = VolleyHelper.getInstance().getImageContainer(avatar_link, new ImageLoader.ImageListener() {
                    @Override
                    public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                        avatarImageView.setImageBitmap(response.getBitmap());
                        imageRequest = null;
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        toast("Get image error=" + error.getMessage());
                    }
                });
            }
        } else {
            selfInfoTextView.setText("Error customrequests");
        }
    }

    public void onCacheTestClick(View view) {
        startActivity(new Intent(this, AvatarsActivity.class));
    }

    @Override
    public void onStop() {
        super.onStop();

        VolleyHelper.getInstance().cancelAll(SELF_INFO_REQUEST_TAG);
        if (imageRequest != null) {
            imageRequest.cancelRequest();
        }
    }

    public void onViewFriendsClick(View view) {
        startActivity(new Intent(this, FriendsListActivity.class));
    }
}
